var { requestInterval } = require("./alloytimer");

class CountDown {
	constructor(now, end) {
	    let self = this;
		this.now = now;
		this.end = end;
		this.interval = interval;

		requestInterval((times)=>{
			this.now += times * (interval/1000);
		}, interval)

		// 3 倍 interval 进行重置一次时间
		requestInterval((times)=>{
			this.getServerTime((timestamps) => {
				// 当前展示的时间是否比之前的快，注意时间跳动
				if (true) {
					this.now = timestamps;
				}
			})
		}, interval * 3)
	}

	render() {
		
	}

	getServerTime(callback) {
		var xhr = new XMLHttpRequest();
		xhr.open('get', '/', true);
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 3) {
				var now = xhr.getResponseHeader('Date');
				callback(new Date(now).valueOf());
			}
		};
		xhr.send(null);
		
		var xhr = new XMLHttpRequest(),
	        self = this,
	        dateStr,
	        dateObj,
	        callBackFlag = false;
        if (!xhr) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("HEAD", location.href, true);
        xhr.onreadystatechange = function() {
            if (!callBackFlag && (xhr.readyState == 4 || xhr.status == 200)) {
                callBackFlag = true;
                dateStr = xhr.getResponseHeader('Date');
                dateObj = new Date(dateStr);
                if (dateStr && dateObj) {
                    callback && callback(dateObj);
                } else {
                    callback && callback(null);
                }
            }
        }
        xhr.send(null);
	}
}


new CountDown({
    interval : 1000,// 时间戳
    nowTime: 20000, // 时间戳
    endTime: 60000, // 时间戳
	render: function(leftTime) {
		console.log(leftTime)
	}
})
